﻿' Copyright (c) 2013  DotNetNuke Corporation
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
Imports DotNetNuke.Entities.Modules.Actions
Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization
Imports DotNetNuke.Modules.AccordionTabs.Components
''' <summary>
''' The View class displays the content
''' 
''' Typically your view control would be used to display content or functionality in your module.
''' 
''' View may be the only control you have in your project depending on the complexity of your module
''' 
''' Because the control inherits from AccordionTabsModuleBase you have access to any custom properties
''' defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
''' 
''' </summary>
Public Class Edit
    Inherits AccordionTabsModuleBase


    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' Page_Load runs when the control is loaded
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Try

            DotNetNuke.Framework.jQuery.RequestDnnPluginsRegistration()
            cmdDeleteAllTabs.Attributes.Add("onClick", "javascript: return confirm('Are you sure you would like to delete ALL of the currently loaded panels?');")
            pnlErrorMessages.Visible = False
            If (Page.IsPostBack = False) Then
                GetAllTabs()
                LoadFirstTab()
                ListDisplayStyles()
            End If
            PrepareUI()
            divInstructions.InnerHtml = Localization.GetString("Instructions", LocalResourceFile)
            divSortInstructions.InnerHtml = Localization.GetString("SortInstructions", LocalResourceFile)
            divDisplayInstructions.InnerHtml = Localization.GetString("DisplayStyleInstructions", LocalResourceFile)
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub GetAllTabs()
        Try
            Dim TabController As New AccordionTabController
            Dim CurrentTabs As AccordionTabs = TabController.GetTabs(TabModuleId)
            lstCurrentTabs.Items.Clear()
            listCurrentTabs.Items.Clear()
            If IsNothing(CurrentTabs) = False Then
                For Each CurrentTab As AccordionTab In CurrentTabs
                    Dim lstCurrentTab As New ListItem
                    If CurrentTab.IsVisible = False Then
                        lstCurrentTab.Text = "[Not Visible] - " + Server.HtmlDecode(CurrentTab.TitleOfTab)
                    Else
                        lstCurrentTab.Text = Server.HtmlDecode(CurrentTab.TitleOfTab)
                    End If
                    lstCurrentTab.Value = CurrentTab.ItemID
                    lstCurrentTabs.Items.Add(lstCurrentTab)
                    lstCurrentTab.Attributes.Add("class", "SortedItem")
                    lstCurrentTab.Attributes.Add("ID", CurrentTab.ItemID)
                    listCurrentTabs.Items.Add(lstCurrentTab)
                Next
            End If
            CurrentTabs = Nothing
            TabController = Nothing
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Private Sub cmdRemoveTab_Click(sender As Object, e As EventArgs) Handles cmdRemoveTab.Click
        Try
            If IsNothing(lstCurrentTabs.SelectedItem) = True Then
            Else
                Dim TabController As New AccordionTabController
                TabController.DeleteTab(TabModuleId, lstCurrentTabs.SelectedItem.Value)
                TabController.Dispose()
                TabController = Nothing
                GetAllTabs()
                If lstCurrentTabs.Items.Count > 0 Then
                    lstCurrentTabs.SelectedIndex = 0
                    LoadExistingTab()
                End If
            End If
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub cmdAddTab_Click(sender As Object, e As EventArgs) Handles cmdAddTab.Click
        Try
            If txtNewTabTitle.Text = "" Then
                pnlErrorMessages.Visible = True
                pnlErrorMessages.Controls.Clear()
                pnlErrorMessages.Controls.Add(New LiteralControl("Please enter in a title for your new accordion tab."))
            Else
                Dim TabController As New AccordionTabController
                Dim NewTab As New AccordionTab
                Dim ExistingTabs As AccordionTabs = TabController.GetTabs(TabModuleId)
                NewTab.ModuleID = TabModuleId
                NewTab.TitleOfTab = Server.HtmlEncode(Trim(txtNewTabTitle.Text))
                txtNewTabContent.HtmlEncode = False
                NewTab.ContentOfTab = Server.HtmlEncode(Trim(txtNewTabContent.Text))
                NewTab.IsVisible = chkNewTabVisible.Checked
                If IsNothing(ExistingTabs) = False Then
                    NewTab.SortOrder = ExistingTabs.Count + 1
                Else
                    NewTab.SortOrder = 1
                End If
                TabController.InsertTab(NewTab)
                TabController.Dispose()
                TabController = Nothing
                NewTab = Nothing
                GetAllTabs()
                PrepareUI()
                txtNewTabTitle.Text = ""
                txtNewTabContent.Text = ""
                pnlErrorMessages.Controls.Clear()
                pnlErrorMessages.Visible = False
            End If
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub lstCurrentTabs_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCurrentTabs.SelectedIndexChanged
        LoadExistingTab()
    End Sub

    Protected Sub cmdModifyTab_Click(sender As Object, e As EventArgs) Handles cmdModifyTab.Click
        Try
            If txtExistingTabTitle.Text = "" Then
                pnlErrorMessages.Visible = True
                pnlErrorMessages.Controls.Clear()
                pnlErrorMessages.Controls.Add(New LiteralControl("Please enter in a title for your modified accordion tab."))
            Else
                Dim TabController As New AccordionTabController
                Dim ModifiedTab As New AccordionTab
                ModifiedTab.ModuleID = TabModuleId
                ModifiedTab.ItemID = lstCurrentTabs.SelectedItem.Value
                ModifiedTab.TitleOfTab = Server.HtmlEncode(Trim(txtExistingTabTitle.Text))
                txtExistingTabContents.HtmlEncode = False
                ModifiedTab.ContentOfTab = Server.HtmlEncode(Trim(txtExistingTabContents.Text))
                ModifiedTab.IsVisible = chkExistingTabVisible.Checked
                ModifiedTab.SortOrder = Int(lblExistingSortPosition.Text)
                TabController.ModifyTab(ModifiedTab)
                TabController.Dispose()
                ModifiedTab = Nothing
                TabController = Nothing
                GetAllTabs()
                PrepareUI()
                txtExistingTabTitle.Text = ""
                txtExistingTabContents.Text = ""
                pnlErrorMessages.Controls.Clear()
                pnlErrorMessages.Visible = False
            End If
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Private Sub LoadExistingTab()
        Try
            If IsNothing(lstCurrentTabs.SelectedItem) = False Then
                Dim TabController As New AccordionTabController
                Dim ExistingTab As New AccordionTab
                ExistingTab = TabController.GetTab(TabModuleId, lstCurrentTabs.SelectedItem.Value)
                txtExistingTabTitle.Text = Server.HtmlDecode(ExistingTab.TitleOfTab)
                txtExistingTabContents.Text = Server.HtmlDecode(ExistingTab.ContentOfTab)
                chkExistingTabVisible.Checked = ExistingTab.IsVisible
                lblExistingSortPosition.Text = ExistingTab.SortOrder.ToString
                TabController.Dispose()
                ExistingTab = Nothing
                TabController = Nothing
            End If
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Private Sub LoadFirstTab()
        Try
            If lstCurrentTabs.Items.Count > 0 And IsNothing(lstCurrentTabs.SelectedItem) = True Then
                Dim TabController As New AccordionTabController
                Dim ExistingTab As New AccordionTab
                ExistingTab = TabController.GetTab(TabModuleId, lstCurrentTabs.Items(0).Value)
                txtExistingTabTitle.Text = Server.HtmlDecode(ExistingTab.TitleOfTab)
                txtExistingTabContents.Text = Server.HtmlDecode(ExistingTab.ContentOfTab)
                chkExistingTabVisible.Checked = ExistingTab.IsVisible
                lblExistingSortPosition.Text = ExistingTab.SortOrder.ToString
                TabController.Dispose()
                ExistingTab = Nothing
                TabController = Nothing
            ElseIf IsNothing(lstCurrentTabs.SelectedItem) = False Then
                Dim TabController As New AccordionTabController
                Dim ExistingTab As New AccordionTab
                ExistingTab = TabController.GetTab(TabModuleId, lstCurrentTabs.SelectedItem.Value)
                txtExistingTabTitle.Text = Server.HtmlDecode(ExistingTab.TitleOfTab)
                txtExistingTabContents.Text = Server.HtmlDecode(ExistingTab.ContentOfTab)
                chkExistingTabVisible.Checked = ExistingTab.IsVisible
                lblExistingSortPosition.Text = ExistingTab.SortOrder.ToString
                TabController.Dispose()
                ExistingTab = Nothing
                TabController = Nothing
            End If
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub cmdDeleteAllTabs_Click(sender As Object, e As EventArgs) Handles cmdDeleteAllTabs.Click
        Try
            Dim TabController As New AccordionTabController
            TabController.DeleteAllTabs(TabModuleId)
            TabController.Dispose()
            TabController = Nothing
            GetAllTabs()
            txtExistingTabTitle.Text = ""
            txtExistingTabContents.Text = ""
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub PrepareUI()
        Try
            panelJQueryCode.Controls.Clear()
            panelJQueryCode.Controls.Add(New LiteralControl("<script type='text/javascript'>" + _
                                            "$('#dnnEditTabs').dnnPanels({" + _
                                                "cookieDays: 0," + _
                                                "cookieMilleseconds: 0" + _
                                            "});" + _
                                            "$('#" + listCurrentTabs.ClientID + "').sortable();" + _
                                            "$('#" + listCurrentTabs.ClientID + "').bind('sortupdate', function(event, ui) {" + _
                                                "var intCurrentSortOrder = 1;" + _
                                                "$( '#" + txtSortedResults.ClientID + "' ).val('');" + _
                                                "$( '.SortedItem' ).each(function(idx, item) {" + _
                                                "$( this ).title = intCurrentSortOrder;" + _
                                                "var strTextToAppend;" + _
                                                "strTextToAppend = $( this ).attr('id') + ':' + intCurrentSortOrder + '|';" + _
                                                "strTextToAppend = $('#" + txtSortedResults.ClientID + "').val() + strTextToAppend;" + _
                                                "$('#" + txtSortedResults.ClientID + "').val(strTextToAppend);" + _
                                                "intCurrentSortOrder = intCurrentSortOrder + 1;" + _
                                            "});});" + _
                                            "</script>"))
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub UpdateSortOrder()
        Try
            Dim TabsController As New AccordionTabController
            Dim intSortOrder As Integer = 1
            '
            'Retrieve Sort Order from Client DOM
            '
            Dim strClientSortOrder As String = txtSortedResults.Value
            If strClientSortOrder = "" Or strClientSortOrder.Length = 0 Then
                divSortInstructions.InnerHtml = ""
                divSortInstructions.InnerHtml = Localization.GetString("ErrorSortInstructions", LocalResourceFile)
            Else
                strClientSortOrder = Left(strClientSortOrder, strClientSortOrder.Length - 1)
                Dim strSortOrderPairs() As String = strClientSortOrder.Split("|")
                If strSortOrderPairs.Count = listCurrentTabs.Items.Count * 2 Then
                    Dim collSortOrderPairs As System.Collections.Generic.IEnumerable(Of String)
                    collSortOrderPairs = strSortOrderPairs.Skip(listCurrentTabs.Items.Count)
                    For Each strCurrentSortedItem As String In collSortOrderPairs
                        Dim CurrentTab As AccordionTab = TabsController.GetTab(TabModuleId, strCurrentSortedItem.Split(":")(0))
                        CurrentTab.SortOrder = Int(strCurrentSortedItem.Split(":")(1))
                        TabsController.ModifyTabSortOrder(CurrentTab)
                        intSortOrder += 1
                    Next
                    pnlErrorMessages.Visible = False
                ElseIf strSortOrderPairs.Count = listCurrentTabs.Items.Count Then
                    For Each strCurrentSortedItem As String In strSortOrderPairs
                        Dim CurrentTab As AccordionTab = TabsController.GetTab(TabModuleId, strCurrentSortedItem.Split(":")(0))
                        CurrentTab.SortOrder = Int(strCurrentSortedItem.Split(":")(1))
                        TabsController.ModifyTabSortOrder(CurrentTab)
                        intSortOrder += 1
                    Next
                    pnlErrorMessages.Visible = False
                Else
                    pnlErrorMessages.Visible = True
                    pnlErrorMessages.Controls.Clear()
                    pnlErrorMessages.Controls.Add(New LiteralControl("There was a problem with getting the sorted order of the tabs. Please contact the developer."))
                End If
                TabsController.Dispose()
                TabsController = Nothing
            End If
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub cmdCloseEdit_Click(sender As Object, e As EventArgs) Handles cmdCloseEdit.Click
        Response.Redirect(Common.Globals.NavigateURL(TabId))
    End Sub

    Protected Sub cmdUpdateSort_Click(sender As Object, e As EventArgs) Handles cmdUpdateSort.Click
        UpdateSortOrder()
        GetAllTabs()
        PrepareUI()
    End Sub

    Protected Sub ListDisplayStyles()
        Try
            Dim TabsController As New AccordionTabController
            Dim CurrentStyles As DisplayStyles

            ddlDisplayStyle.Items.Clear()

            CurrentStyles = TabsController.GetDisplayStyles(TabModuleId)

            If CurrentStyles.Count = 0 Then
                ddlDisplayStyle.Items.Add("Accordion")
                ddlDisplayStyle.Items.Add("Tabs")
                ddlDisplayStyle.Items.Add("'jShowOff' - Content Slider")
                ddlDisplayStyle.SelectedIndex = 0
            Else
                Select Case CurrentStyles.Item(0).DisplayStyle
                    Case "Accordion"
                        ddlDisplayStyle.Items.Add(CurrentStyles.Item(0).DisplayStyle + " - Selected")
                        ddlDisplayStyle.Items.Add("Tabs")
                        ddlDisplayStyle.Items.Add("'jShowOff' - Content Slider")
                        ddlDisplayStyle.SelectedIndex = 0
                    Case "Tabs"
                        ddlDisplayStyle.Items.Add("Accordion")
                        ddlDisplayStyle.Items.Add(CurrentStyles.Item(0).DisplayStyle + " - Selected")
                        ddlDisplayStyle.Items.Add("'jShowOff' - Content Slider")
                        ddlDisplayStyle.SelectedIndex = 1
                    Case "'jShowOff' - Content Slider"
                        ddlDisplayStyle.Items.Add("Accordion")
                        ddlDisplayStyle.Items.Add("Tabs")
                        ddlDisplayStyle.Items.Add(CurrentStyles.Item(0).DisplayStyle + " - Selected")
                        ddlDisplayStyle.SelectedIndex = 2
                    Case Else
                        ddlDisplayStyle.Items.Add("Accordion")
                        ddlDisplayStyle.Items.Add("Tabs")
                        ddlDisplayStyle.Items.Add("'jShowOff' - Content Slider")
                        ddlDisplayStyle.SelectedIndex = 0
                End Select
            End If
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub ddlDisplayStyle_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlDisplayStyle.SelectedIndexChanged
        Try
            UpdateDisplayStyle()
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub

    Protected Sub UpdateDisplayStyle()
        Try
            If IsNothing(ddlDisplayStyle.SelectedItem) = False Then
                Dim TabsController As New AccordionTabController
                TabsController.DeleteAllDisplayStyles(TabModuleId)
                Dim NewDisplayStyle As New DisplayStyle
                NewDisplayStyle.ModuleID = TabModuleId
                If Right(ddlDisplayStyle.SelectedItem.Text, 11) = " - Selected" Then
                    NewDisplayStyle.DisplayStyle = Left(ddlDisplayStyle.SelectedItem.Text, ddlDisplayStyle.Text.Length - 11)
                Else
                    NewDisplayStyle.DisplayStyle = ddlDisplayStyle.SelectedItem.Text
                End If
                TabsController.InsertDisplayStyle(NewDisplayStyle)
                divDisplayInstructions.InnerHtml = ""
                divDisplayInstructions.InnerHtml = Localization.GetString("DisplayStyleInstructions", LocalResourceFile) + _
                    Localization.GetString("DisplayStyleUpdate", LocalResourceFile) + "<p><strong>" + NewDisplayStyle.DisplayStyle + _
                    "</strong></p><p>" + NewDisplayStyle.DisplayStyleNotes + "</p>"
                ListDisplayStyles()
            End If
        Catch exc As Exception
            Exceptions.ProcessModuleLoadException(Me, exc)
        End Try
    End Sub
End Class